package com.bugbuff.dubbo.server.controller;


import cn.hutool.core.util.ObjectUtil;
import com.bugbuff.common.utils.NoAuthorization;
import com.bugbuff.common.vo.ErrorResult;
import com.bugbuff.dubbo.server.config.CreateValidateCode;
import com.bugbuff.dubbo.server.service.AdminService;
import com.bugbuff.dubbo.server.vo.AdminVo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

@RestController
@RequestMapping("management/system/users")
@Slf4j
public class AdminController {

    /*
    * 导入adminService
    * */
    @Autowired
    private AdminService adminService;

    //private static Logger log = LoggerFactory.getLogger(AdminController.class);



    /**
     * 登录
     * @param param 参数
     * @return
     */
    @PostMapping("login")
    @NoAuthorization
    public ResponseEntity<Object> login(@RequestBody Map<String,String> param){
        //获取账号
        String username = param.get("username");
        //获取密码
        String password = param.get("password");
        //获取验证码
        String code = param.get("verificationCode");
        //获取uuid
        String uuid = param.get("uuid");
        //请求接收前端返回的信息
        Map<String,String> token = adminService.login(username,password,code,uuid);
        //判断前端返回的信息
        if (ObjectUtil.isNotEmpty(token)){
            //没有错误信息，返回前端200，表示请求成功
            if (!(token.containsKey("message"))){
                return ResponseEntity.ok(token);
            }
        }
        //有错误信息，返回前端500以及错误信息，表示请求失败
        //ErrorResult errorResult = ErrorResult.builder().errCode("000006").errMessage("登录失败！！！").build();
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).contentType(MediaType.APPLICATION_JSON_UTF8).body(token);
    }


    /**
     * 生成登录页面的图片验证码
     * @param response 响应
     * @param request 请求
     * @throw
     */
    @GetMapping("verification")
    @NoAuthorization
    public void getVerificationCode( @RequestParam("uuid") String uuid, HttpServletResponse response, HttpServletRequest request) {
        OutputStream outputStream =null;
        try {
            //创建输出流
            outputStream = response.getOutputStream();
            //获取session
            HttpSession session = request.getSession();
            //获取验证码
            CreateValidateCode createValidateCode = new CreateValidateCode();
            String generateVerifyCode = createValidateCode.getString();
            //String generateVerifyCode = "1234";
            //将验证码存入session，做登录验证
            session.setAttribute(uuid,generateVerifyCode);
            log.info("开始获取验证码session uuid为{},验证码为{}", session.getId(), generateVerifyCode);
            //获取验证码图片
            BufferedImage image = createValidateCode.getImage();
            ImageIO.write(image, "png", outputStream);
            outputStream.flush();


            adminService.saveCode(uuid,generateVerifyCode);

        } catch (IOException e) {
            log.error("获取验证码图片异常！", e);
        }finally {
            if(outputStream!=null){
                //关流
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error("关闭流失败！", e);
                }
            }
        }
    }


    /**
     * 用户登出操作
     * @param token
     */
    @PostMapping("logout")
    public void logout(@RequestHeader("Authorization") String token){
       adminService.logout(token);
    }


    /**
     * 用户基本信息
     * @return 用户基本信息对象
     */
    @PostMapping("profile")
    public ResponseEntity<Object> profile(){
        //获取用户基本信息
        AdminVo adminVo = adminService.profile();
        //判断用户信息是否为空
        if (ObjectUtil.isNotEmpty(adminVo)){
            //不为空，直接返回用户信息
            return ResponseEntity.ok(adminVo);
        }
        //返回对应的错误信息
        ErrorResult errorResult = ErrorResult.builder().errCode("000007").errMessage("获取用户信息错误").build();
        //控制台打印
        log.error("获取用户信息错误");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }


}
